# jieba库 -- 用于分词
import jieba
# 用于存储词云图
from PIL import Image
# n维数组
import numpy as np
# 绘制词云图
from matplotlib import pyplot as plt
# 用于写词云图
from wordcloud import WordCloud
# 设置随机数
import random

# 引入utils文件中的query文件下的querys方法
from utils.query import querys
# 引入utils文件中的utils文件下的typeList1方法
from utils.utils import typeList1

# 获取评论词云图
def getImageByComments(comments):
    text = ''
    # 获取评论内容 -- 将所有人的评论累加为一个字符串
    for i in comments:
        text += i['content']

    # 分词
    cut = jieba.cut(text)
    # 将分词结果按空格分隔
    string = ' '.join(cut)
    # print(string)
    # 打开一张用于画词云图的图片
    img = Image.open('./static/img/comments.png')
    #
    img_arr = np.array(img)
    wc = WordCloud(
        background_color='white',
        mask=img_arr,
        # 字体地址
        font_path='./fonts/simhei.ttf'
    )
    # 将处理后的分词结果转换成词云图
    wc.generate_from_text(string)

    # 绘制图片
    plt.figure(1)
    plt.figure(1)
    plt.imshow(wc)
    plt.axis('off')

    # 存储词云图
    randomInt = random.randint(1, 100000000)
    fig_file = f'./static/img/评论词云图/{randomInt}.png'
    plt.savefig(fig_file)

    return fig_file

# 获取标题词云图、简介词云图、演员名称词云图
def getImageByOthers(field, targetImage, resImage):
    if field == 'casts':
        text = ''
        data = typeList1('casts')
        for i in data:
            text += i
    else:
        text = ''
        # 从数据库中获取相应字段field
        sql = 'select {} from movies'.format(field)
        data = querys(sql, [], 'select')
        # 获取评论内容 -- 将所有人的评论累加为一个字符串
        for i in data:
            text += i[0]

    # 分词
    cut = jieba.cut(text)
    # 将分词结果按空格分隔
    string = ' '.join(cut)
    # print(string)
    # 打开一张用于画词云图的图片
    img = Image.open(targetImage)
    #
    img_arr = np.array(img)
    wc = WordCloud(
        background_color='white',
        mask=img_arr,
        # 字体地址
        font_path='./fonts/simhei.ttf'
    )
    # 将处理后的分词结果转换成词云图
    wc.generate_from_text(string)

    # 绘制图片
    plt.figure(1)
    plt.figure(1)
    plt.imshow(wc)
    plt.axis('off')

    # 存储词云图
    plt.savefig(resImage)

    return resImage

# test
# getImageByOthers('title', './static/img/title.png', './static/img/title_cloud.png')
# getImageByOthers('summary', './static/img/summary.png', './static/img/summary_cloud.png')
# getImageByOthers('casts', './static/img/casts.png', './static/img/casts_cloud.png')